package circuits;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public abstract class Operator extends Operation implements OperationListener{

	protected Collection<Operation> operands;
	
	public Operator(){
		this.operands = new ArrayList<Operation>();
	}
	
	public boolean isOperand(Operation operation){
		return this.operands.contains(operation);
	}
	
	public boolean addOperand(Operation operation){
		if ((operation != this)&&(!this.isOperand(operation))){
			operation.addOperationListener(this);
			this.operands.add(operation);
			return true;
		}
		return false;
	}
	
	public boolean removeOperand(Operation operation){
		if ((operation != this)&&(this.isOperand(operation))){
			operation.removeOperationListener(this);
			this.operands.remove(operation);
			return true;
		}
		return false;
	}
	
	private boolean allOperandResultsObtained(){
		Iterator<Operation> operandsIterator = this.operands.iterator();
		while (operandsIterator.hasNext()){
			Operation operation = operandsIterator.next();
			if (!operation.resultObtained) return false;
		}
		return true;
	}

	@Override
	public void onOperationResultObtained(Operation operand) {
		if (this.allOperandResultsObtained()){
			this.calculateResult();
		}
	}

	@Override
	protected void getOperandResult() {
		Iterator<Operation> operandsIterator = this.operands.iterator();
		while (operandsIterator.hasNext()){
			Operation operation = operandsIterator.next();
			operation.getOperandResult();
		}
	}
	
	protected abstract void calculateResult();
}
